package com.lyy.cloud.utils.des;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @author liushiwei
 * @Description: 加密解密算法
 * @Title: DesUtil
 * @ProjectName zsdy-v10
 * @date 2019/7/26 11:16
 */
@Slf4j
public class DesUtil {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //以下是加密方法algorithm="AES"的测试
        System.out.println(DesUtil.getInstance("32222222").getEnCodeString("456787jkljjojoijn,"));
        //将上面的密文解密：
        System.out.println(DesUtil.getInstance("32222222").getDecodeString("gdimBYwSGEX/Ru4QH/nRbQ=="));
    }
    private SecretKey key=null;//密钥
    //定义 加密算法,可用 DES,DESede,Blowfish,AES
    //不同的加密方式结果会不同
    private static String algorithm="AES";
    private static DesUtil desUtil=null;
    public DesUtil(){}
    public static DesUtil getInstance(String strKey){
        desUtil=new DesUtil();
        desUtil.createKey(strKey);
        return desUtil;
    }
    /**
     * algorithm 算法
     * @param strKey
     */
    public void createKey(String strKey){
        try{
            KeyGenerator kg= KeyGenerator.getInstance(DesUtil.algorithm);
            byte[] bt=strKey.getBytes("UTF-8");
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(bt);
            kg.init(128, secureRandom);
            this.setKey(kg.generateKey());
        }catch(Exception e){
            log.error("初始化密钥出现异常"+e);
        }
    }
    /**
     * 加密方法，返回密文
     * cipher 密码
     * @param dataStr
     */
    public String getEnCodeString(String dataStr){
        byte[] miwen=null;//密文
        byte[] mingwen=null;//明文
        Cipher cipher;
        String result="";//密文字符串
        try{
            mingwen=dataStr.getBytes("UTF-8");
            cipher= Cipher.getInstance(DesUtil.algorithm);
            cipher.init(Cipher.ENCRYPT_MODE, this.getKey());
            miwen=cipher.doFinal(mingwen);
//            BASE64Encoder base64en = new BASE64Encoder();
            Base64.Encoder encoder = Base64.getEncoder();
            result=encoder.encodeToString(miwen);//或者可以用下面的方法得到密文，结果是不一样的，都可以正常解密
            result = result.replace("\n","").replace("\r","");
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 解密方法，返回明文
     * @param codeStr
     * @return
     */
    public String getDecodeString(String codeStr){
        // 向上兼容 rt.jar包删除
//        BASE64Decoder base64De = new BASE64Decoder();
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] miwen=null;
        byte[] mingwen=null;
        String resultData="";//返回的明文
        Cipher cipher;
        try{
            miwen=decoder.decode(codeStr);
            cipher=Cipher.getInstance(DesUtil.algorithm);
            cipher.init(Cipher.DECRYPT_MODE, this.getKey());
            mingwen=cipher.doFinal(miwen);
            resultData = new String(mingwen,"UTF-8");
        }catch(Exception e){
            log.info("解密失败");
            return null;
        }
        return resultData;
    }

    //二行制转字符串
    public String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
            if (n < b.length - 1)
                hs = hs + ":";
        }
        return hs.toUpperCase();
    }
    public SecretKey getKey() {
        return key;
    }
    public void setKey(SecretKey key) {
        this.key = key;
    }
    public static String getAlgorithm() {
        return algorithm;
    }

    /**
     * 加密未加密过的参数
     * @param value 参数
     * @param secretKey 密钥
     * @return
     */
    public static String getEnCodeByUntreated(String value,String secretKey){
        if(StringUtils.isNotBlank(value)){

            String decodeString = DesUtil.getInstance(secretKey).getDecodeString(value);

            if(StringUtils.isBlank(decodeString)){
                // 加密
                String valueSecret = DesUtil.getInstance(secretKey).getEnCodeString(value);
                return valueSecret;
            }
        }
        return value;
    }

    /**
     * 解密失败则返回原值
     * @param value
     * @param secretKey
     * @return
     */
    public static String getDecodeByUntreated(String value,String secretKey){
        if(StringUtils.isNotBlank(value)){

            String decodeString = DesUtil.getInstance(secretKey).getDecodeString(value);

            if(StringUtils.isNotBlank(decodeString)){

                return decodeString;
            }
        }
        return value;
    }
}
